<template>
    <div v-loading="$store.state.saving"
    element-loading-text="保存中" element-loading-spinner="el-icon-loading"
    element-loading-background = "rgba(255,255,255,0.8)">
        <el-tabs>
            <el-tab-pane label="销售机会">
                <el-form :model="addOppoForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm actForm inline3__" style="overflow: hidden">
                    <el-form-item label="机会名称" prop="oppoName">
                        <el-input v-model="addOppoForm.oppoName" placeholder="可不录，自动生成"></el-input>
                    </el-form-item>
                    <el-form-item label="对应客户" prop="customer.customerId" class="tryy inline3__">
                        <template>
                            <el-select v-model="addOppoForm.customer" placeholder="请选择" value-key="customerId" @change="judgeIsOppo(addOppoForm.customer)" width="100%">
                                <el-option
                                        v-for="cus in customer"
                                        :key="cus.customerId"
                                        :label="cus.customerName"
                                        :value="cus">
                                </el-option>
                            </el-select>
                        </template>
                    </el-form-item>
                    <el-form-item label="预计成交日" prop="planIdealTime" >
                        <template>
                            <div class="block">
                                <el-date-picker
                                        v-model="addOppoForm.planIdealTime"
                                        type="date"
                                        placeholder="选择日期"
                                        :picker-options="outDateLimit">
                                </el-date-picker>
                            </div>
                        </template>
                    </el-form-item>
                    <el-form-item label="详细信息" prop="detail">
                        <el-input v-model="addOppoForm.detail"></el-input>
                    </el-form-item>
                    <el-form-item label="相关附件" prop="">
                        <el-input v-model="addOppoForm.aboutDocument" :readonly="true" placeholder style="line-height:38px">
                            <el-tag @close="close_tag(file)" type="info" closable slot="prefix" v-for="file in flieList" :key="file.uid">{{ file.name }}</el-tag>
                            <el-upload multiple slot="append"  action="upload" :show-file-list="false" :on-success="upload_success">
                                <el-button size="small">点击上传文件</el-button>
                            </el-upload>
                        </el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
                    </el-form-item>
                </el-form>
            </el-tab-pane>
            <el-tab-pane label="意向产品">
                <el-button @click="addProductDialogVisible = true">添加产品</el-button>
                <el-table  :data="addOppoForm.oppoProList">
                    <el-table-column label="图片">
                        <template slot-scope="s">
                            <el-image :src="s.row.productDetail.proImgSrc" style="width:40px;height:40px;"></el-image>
                        </template>
                    </el-table-column>
                    <el-table-column prop="productDetail.product.productName" label="名称"></el-table-column>
                    <el-table-column label="规格属性">
                        <template slot-scope="s">
                            <span v-for="item in s.row.productDetail.abilities" :key="item.abilityId">{{item.abilityName}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="proDetail.product.productBrand" label="品牌"></el-table-column>
                    <el-table-column label="报价">
                        <template slot-scope="s">
                            <span>{{s.row.offer}}元</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="成本价">
                        <template slot-scope="s">
                            <span>{{s.row.productDetail.proPrice*0.6}}元</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="数量" prop="proCount" width="100">
                        <template slot-scope="s">
                            <el-input type="number" v-model="s.row.productNum"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="金额">
                        <template slot-scope="s">
                            {{ s.row.offer * s.row.productNum }}
                        </template>
                    </el-table-column>
                    <el-table-column label="盈利">
                        <template slot-scope="s">
                            {{ ((s.row.offer - s.row.productDetail.proPrice*0.6) * s.row.productNum).toFixed(2) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="s">
                            <el-button size="mini" type="danger" icon="el-icon-delete" circle @click="delete_product(s.row)"></el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
        </el-tabs>
        <el-dialog title="添加产品" :visible.sync="addProductDialogVisible" width="90%" append-to-body>
            <add-offerproduct ref="refAddProduct"></add-offerproduct>
        </el-dialog>
    </div>
</template>

<script>
    import {formatTimeToStr} from '@/assets/format.js'
    export default {
        name: "addOppoForm",
        components:{
            'add-offerproduct':resolve => require(["./add_offerproduct"],resolve)			// 产品添加
        },
        props:{},
        data() {
            return {
                customer:[],             //客户列表
                addOppoForm: {
                    oppoId:0,
                    oppoName: "",
                    stateDate:new Date(),       //添加时间
                    planIdealTime:new Date(),  //计划成功时间
                    saleSource:"",      //报价
                    detail:"",          //详细信息
                    aboutDocument:"",   //相关文件
                    nextContactTime:new Date(),  //推进到当前阶段的时间
                    customer:{
                        customerId:'',
                        customerName:'',
                    },        //客户数据源
                    worker:"",          //跟进者数据源
                    state:{oppoStateId:1},
                    isOn:1,
                    oppoProList:[],
                },
                flieList:[],        //文件
                addProductDialogVisible:false,
                rules: {
                    "customer.customerId": [
                        { required: true, message: '请选择客户', trigger: 'blur' }
                    ],
                    planIdealTime: [
                        { required: true,  message: '请选择你计划的日期', trigger: 'change' }
                    ],
                    detail: [
                        { required: true, message: '请填写机会详情', trigger: 'blur' }
                    ]
                },
                judgeOppo:[],
                oppotunity:[],
                // tags: [
                //     { name: '标签一', type: '' }
                // ]
                behaviors:{
                    behavior:{
                        behaviorId:11,
                    },
                    customer:{

                    },
                    actionRecord:null,
                },
                outDateLimit:{},        //日期选择器的禁用标志
            };
        },
        methods: {
            get_customer(){
                this.axios.get("api/customer/select_cus",{params:{}})
                .then(v=>{
                    this.customer = v.data;
                }).catch(() => {
                    this.global.mes_error("获取客户数据失败！")
                })
            },
            //判断此用户是否机会用户
            judgeIsOppo(customer){
                this.axios.get("api/oppo-sale/judgeIsOppo",{params:{"customerId":customer.customerId}})
                    .then(v=>{
                        if(v.data == 3){
                            this.global.confirm("提示","此用户已是机会客户，不能再添加销售机会！点确认搜索",
                                () => {
                                    this.clearaddOppoForm()
                                    this.$parent.$parent.search = customer.customerName
                                    this.$parent.$parent.saveOppoDialogVisible = false
                                },() => {
                                    this.global.mes_message("取消")
                                    this.clearaddOppoForm()
                                    this.$parent.$parent.saveOppoDialogVisible = false
                                })
                        }
                        if(v.data == 4){
                            this.global.confirm("提示","此用户已是合同客户，不能再添加销售机会！点确认前往查看",
                                () => {
                                    //跳转到合同详情页面
                                    this.clearaddOppoForm()
                                    this.$router.push('/contract-index')
                                    this.$parent.$parent.saveOppoDialogVisible = false
                                },() => {
                                    this.global.mes_message("取消")
                                    this.clearaddOppoForm()
                                    this.$parent.$parent.saveOppoDialogVisible = false
                                })
                        }
                    }).catch()
            },
            delete_product(row){
                this.global.confirm("提示","确认删除？",
                    () => {
                        this.addOppoForm.oppoProList.splice(this.addOppoForm.oppoProList.indexOf(row),1)
                        this.global.mes_success("删除成功")
                    },() => {
                        this.global.mes_message("取消删除")
                    })
            },
            /* 删除文件 */
            close_tag(file){
                window.console.log(file)
                this.flieList.splice(this.flieList.indexOf(file),1)
            },
            /* 文件上传成功函数 */
            upload_success(response,file,flie_list){
                this.flieList = flie_list
            },
            /* 表单提交dialogVisible2*/
            submitForm(formName) {
                if(this.addOppoForm.oppoProList.length === 0){
                    this.global.mes_error("请添加商品!")
                }else{
                    this.addOppoForm.worker = this.$store.state.user
                    this.addOppoForm.state.oppoStateId = 1
                    window.console.log(this.addOppoForm)
                    this.$refs[formName].validate((valid) => {
                        if (valid) {
                            if(!this.addOppoForm.oppoName){
                                const now = new Date()
                                const month = now.getMonth() + 1
                                const day = now.getDate()
                                let no =  now.getFullYear()+(month<10? "0"+month:month )+(day<10?"0"+day:day)
                                let ran = parseInt(Math.random()*10000000+1,10)
                                String.prototype.padLeft =
                                    Number.prototype.padLeft = function(total, pad) {
                                        return (Array(total).join(pad || 0) + this).slice(-total);
                                    }
                                const str = ran.padLeft(8)
                                const result = no+str
                                this.addOppoForm.oppoName = "oppo"+result
                            }
                            if(this.addOppoForm.oppoId === 0){
                                this.behaviors.customer = this.addOppoForm.customer
                                this.axios.post("api/actrecord/saveBehavior",this.behaviors)
                                    .then(v=>{
                                        window.console.log(v)
                                        this.behaviors={
                                            behavior:{
                                                behaviorId:11,
                                            },
                                            customer:{
                                            },
                                            actionRecord:null,
                                        }
                                    }).catch()
                            }
                            /* 处理文件url */
                            if (this.flieList){
                                let str = ""
                                this.flieList.forEach(file => {
                                    str += file.response + ","
                                })
                                this.addOppoForm.aboutDocument = str.substring(0, str.lastIndexOf(","))
                            }
                            this.axios.post('api/oppo-sale/saveOppo',this.addOppoForm)
                                .then(v=>{
                                    window.console.log(v)
                                    this.$parent.$parent.get_oppoState()
                                    this.$parent.$parent.saveOppoDialogVisible = false
                                    //重置数据
                                    this.clearaddOppoForm()
                                    this.$parent.$parent.drawer = false
                                })
                                .catch(() => {
                                    this.$parent.saveOppoDialogVisible = false
                                    this.global.mes_error("提交失败1")
                                })
                        } else {
                            this.$parent.saveOppoDialogVisible = false
                            this.global.mes_error("数据错误，提交失败")
                            return false;
                        }
                    });
                }
            },
            //清空addOppoForm
            clearaddOppoForm(){
                this.addOppoForm = {
                    oppoId:0,
                    oppoName: "",
                    stateDate:new Date(),       //推进到当前进度的试卷
                    planIdealTime: new Date(),  //计划成功时间
                    saleSource:"",      //报价
                    detail:"",          //详细信息
                    aboutDocument:"",   //相关文件
                    nextContactTime:"",  //下次访问时间
                    customer:{
                        customerId:"",
                        customerName:"",
                    },        //客户数据源
                    worker:"",          //跟进者数据源
                    state:{oppoStateId:1},
                    isOn:1,
                    oppoProList:[],
                }
            },
            beforeUpload(file) {
                //规定上传的文件
                var testmsg=file.name.substring(file.name.lastIndexOf('.')+1)
                const extension = testmsg
                const extension2 = testmsg
                if(!extension && !extension2) {
                    this.$message({
                        message: '上传文件只能是 xls、xlsx格式!',
                        type: 'warning'
                    });
                }
                //规定上传格式的大小
                const isLt2M = file.size / 1024 / 1024 < 100
                if(!isLt2M) {
                    this.$message({
                        message: '上传文件大小不能超过 100MB!',
                        type: 'warning'
                    });
                }
                return extension || extension2 && isLt2M
            },
        },
        created:function(){
            this.get_customer();
            this.outDateLimit={
                disabledDate(time) {
                    return time.getTime() < new Date().getTime()-3600 * 1000 * 24;
                }
            }
        },
        filters: {
            formatDate: function(time) {
                if(time!=null&&time!="")
                {
                    var date = new Date(time);
                    return formatTimeToStr(date, "yyyy-MM-dd");
                }else{
                    return "";
                }
            }
        },
        computed:{
            // customer_options(){
            //     let array = []
            //     this.cusList.forEach(item => {
            //         let obj = {}
            //         obj.value = item.customerId
            //         obj.label = item.customerName
            //         array.push(obj)
            //     });
            //     return array
            // }
        }

    }
</script>

<style>
    .tryy .el-select {
        width:106% !important;
    }
    .inline3__{width:95%!important;display:inline-block}
    .actForm .el-form-item{width: 100%;margin-bottom: 22px !important;}
    .actForm-select .el-select input[type="text"]{padding-left: 10px;width: 300px}
    .actForm-document .el-upload-dragger{width: 669px;height: 40px;border: 1px solid #d9d9d9;}
</style>